package com.gjh.xiaokabang2code.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gjh.xiaokabang2code.common.*;
import com.gjh.xiaokabang2code.mapper.*;
import com.gjh.xiaokabang2code.model.*;
import com.gjh.xiaokabang2code.model.request.CloseRt;
import com.gjh.xiaokabang2code.model.response.FinderRs;
import com.gjh.xiaokabang2code.model.response.LoginRs;
import com.gjh.xiaokabang2code.service.SearchFinderService;
import com.gjh.xiaokabang2code.service.SuccessMatchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author tsin0
 * @description 针对表【search_finder】的数据库操作Service实现
 * @createDate 2024-03-08 08:58:29
 */
@Service
public class SearchFinderServiceImpl extends ServiceImpl<SearchFinderMapper, SearchFinder>
        implements SearchFinderService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private BankcardMapper bankcardMapper;

    @Resource
    private SearchLoserMapper searchLoserMapper;

    @Resource
    private SuccessMatchService successMatchService;

    @Resource
    private SuccessMatchMapper successMatchMapper;

    @Autowired
    private CustomMailSender customMailSender;

    public static final String SALT = "XiaoKabang2Bygjh2003";

    @Override
    public String loseToList(LoginRs loginUser) throws Exception {
        String uId = loginUser.getUId();
        if (uId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空(S2001)");
        }
        QueryWrapper<Bankcard> bankcardQueryWrapper = new QueryWrapper<>();
        bankcardQueryWrapper.eq("u_id", uId);
        List<Bankcard> bankcards = bankcardMapper.selectList(bankcardQueryWrapper);
        if (bankcards.isEmpty()) {
            throw new BusinessException(ErrorCode.REPEATING_DATA, "数据库没有该条数据(S2003)");
        }
        if (bankcards.size() > 1) {
            throw new BusinessException(ErrorCode.REPEATING_DATA, "数据数目大于1?(S2004)");
        }
        Bankcard bankcard = bankcards.get(0);
        if(bankcard.getUBankcard()==null||(bankcard.getUBankcard().isEmpty())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空(S2001)");
        }
        QueryWrapper<SearchLoser> searchLoserQueryWrapper = new QueryWrapper<>();
        searchLoserQueryWrapper.eq("u_bankcard", bankcard.getUBankcard());
        searchLoserQueryWrapper.eq("status", 0);
        List<SearchLoser> searchLosers = searchLoserMapper.selectList(searchLoserQueryWrapper);
        if (searchLosers.isEmpty()) {
            QueryWrapper<SearchFinder> searchFinderQueryWrapper = new QueryWrapper<>();
            searchFinderQueryWrapper.eq("u_bankcard", bankcard.getUBankcard());
            searchFinderQueryWrapper.eq("status", 0);
            long count = this.count(searchFinderQueryWrapper);
            if (count >= 1) {
                return "information has exist in SearchFinder";
            }
            bankcard.setBankcardStatus(1);
            bankcardMapper.update(bankcard, bankcardQueryWrapper);
            SearchFinder searchFinder = new SearchFinder();
            searchFinder.setUBankcard(bankcard.getUBankcard());
            searchFinder.setLoserUid(uId);
            searchFinder.setCreateTime(new Date());
            boolean save = this.save(searchFinder);
            if (!save) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "新增查询捡到同学列表失败(S2002)");
            }
            return "add success but search is error";
        }
        if (searchLosers.size() > 1) {
            throw new BusinessException(ErrorCode.REPEATING_DATA, "数据数目大于1?(S2004)");
        }

        SearchLoser searchLoser = searchLosers.get(0);
        searchLoser.setStatus(1);
        int update = searchLoserMapper.update(searchLoser, searchLoserQueryWrapper);
        if (update != 1) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "更新失败(S2002)");
        }
        String fourBankcard = HideCharactersUtil.convertToFourDigits(new DesUtil(SALT).decrypt(bankcard.getUBankcard(), "CBC"));
        String formattedDate = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm");
        String stuNumMail = "vm" + searchLoser.getFinderUid() + "@jzxy.edu.cn";
        customMailSender.MailSendToFinder(stuNumMail, formattedDate, fourBankcard);
        SuccessMatch successMatch = new SuccessMatch();
        successMatch.setUBankcard(bankcard.getUBankcard());
        successMatch.setFinderUid(searchLoser.getFinderUid());
        successMatch.setLoserUid(uId);
        successMatch.setCreateTime(new Date());
        boolean save = successMatchService.save(successMatch);
        if (!save) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "新增成功列表失败(S2002)");
        }
        return "search success";
    }

    @Override
    public FinderRs searchFinder(LoginRs loginUser) throws Exception {
        String uId = loginUser.getUId();
        if (uId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空(S2001)");
        }
        QueryWrapper<Bankcard> bankcardQueryWrapper = new QueryWrapper<>();
        bankcardQueryWrapper.eq("u_id", uId);
        List<Bankcard> bankcards = bankcardMapper.selectList(bankcardQueryWrapper);
        if (bankcards.isEmpty()) {
            throw new BusinessException(ErrorCode.REPEATING_DATA, "数据库没有该条数据(S2003)");
        }
        if (bankcards.size() > 1) {
            throw new BusinessException(ErrorCode.REPEATING_DATA, "数据数目大于1?(S2004)");
        }
        Bankcard bankcard = bankcards.get(0);
        QueryWrapper<SuccessMatch> successMatchQueryWrapper = new QueryWrapper<>();
        successMatchQueryWrapper.eq("u_bankcard", bankcard.getUBankcard());
        successMatchQueryWrapper.eq("success_status", 0);
        List<SuccessMatch> successMatches = successMatchMapper.selectList(successMatchQueryWrapper);
        if (successMatches.isEmpty()) {
            return new FinderRs();
        }
        if (successMatches.size() > 1) {
            throw new BusinessException(ErrorCode.REPEATING_DATA, "数据数目大于1?(S2004)");
        }
        SuccessMatch successMatch = successMatches.get(0);
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("u_id", successMatch.getFinderUid());
        List<User> users = userMapper.selectList(userQueryWrapper);
        if (users.isEmpty()) {
            throw new BusinessException(ErrorCode.REPEATING_DATA, "数据库没有该条数据(S2001)");
        }
        if (users.size() > 1) {
            throw new BusinessException(ErrorCode.REPEATING_DATA, "数据数目大于1?(S2002)");
        }
        //库里有
        User user = users.get(0);
        FinderRs finderRs = new FinderRs();
        if (user.getNamePrivacy() == 0) {
            finderRs.setUId(user.getUId());
            finderRs.setUName(user.getUName());
            finderRs.setUClass(user.getUClass());
            finderRs.setUDepartment(user.getUDepartment());
        }
        if (user.getNamePrivacy() == 1) {
            finderRs.setUId(user.getUId());
            finderRs.setUPhone(new DesUtil(SALT).decrypt(user.getUPhone(), "CBC"));
        }
        return finderRs;
    }

    @Override
    public Boolean closeSearchFinder(CloseRt closeRt, LoginRs loginUser) {
        String uId = loginUser.getUId();
        if (uId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "uId为空");
        }
        if (!uId.equals(closeRt.getUId())) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "系统内部严重错误");
        }
        QueryWrapper<SuccessMatch> successMatchQueryWrapper = new QueryWrapper<>();
        successMatchQueryWrapper.eq("loser_uid", uId);
        successMatchQueryWrapper.eq("success_status", 0);
        List<SuccessMatch> successMatches = successMatchMapper.selectList(successMatchQueryWrapper);
        if (successMatches.isEmpty()) {
            return false;
        }
        if (successMatches.size() > 1) {
            throw new BusinessException(ErrorCode.REPEATING_DATA, "数据数目大于1?(S2004)");
        }
        SuccessMatch successMatch = new SuccessMatch();
        successMatch.setSuccessStatus(1);
        int update = successMatchMapper.update(successMatch, successMatchQueryWrapper);
        if (update != 1) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "更新失败(S2002)");
        }
        QueryWrapper<Bankcard> bankcardQueryWrapper = new QueryWrapper<>();
        bankcardQueryWrapper.eq("u_id", uId);
        Bankcard bankcard = new Bankcard();
        bankcard.setBankcardStatus(0);
        int update1 = bankcardMapper.update(bankcard, bankcardQueryWrapper);
        if (update1 != 1) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "更新失败(S2002)");
        }
        return true;
    }
}




